package org.example.c_0_003;

import org.junit.Test;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

/**
 * 锁的对比： LongAdder、AtomicInteger、Synchronized
 */
public class T_Compare_Lock {
    private int count0 = 0;
    private AtomicInteger count1 = new AtomicInteger(0);
    private LongAdder count2 = new LongAdder();

    private void m(){
        for (int i = 0; i < 100000; i++) {
//            synchronized (this){
//                count0++;
//            }
//            count1.incrementAndGet();// 相当于 i++
            count2.increment();
        }
    }

    @Test
    public void run(){
        long start = System.currentTimeMillis();
        ArrayList<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            threads.add(new Thread(this::m));
        }
        threads.forEach(thread -> thread.start());

        threads.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("结果："+count2+"   用时："+(System.currentTimeMillis()-start));
    }
    
}
